<template>
  <view class="address-page">
    <view class="header">
      <view class="title">{{isFromOrder ? '选择收货地址' : '管理收货地址'}}</view>
      <view class="new-btn" @click="createNewAddress">新建</view>
    </view>
    
    <view class="address-list">
      <view v-if="addresses.length === 0" class="empty-tip">
        <text>暂无收货地址</text>
        <text class="add-tip">点击右上角"新建"添加地址</text>
      </view>
      
      <view v-else v-for="(address, index) in addresses" :key="address.id" 
        class="address-item" 
        :class="{'selectable': isFromOrder}"
        @click="selectAddress(address)">
        <view class="address-content">
          <view class="contact-info">
            <text class="name">{{address.name}}</text>
            <text class="phone">{{address.phone}}</text>
            <text v-if="address.isDefault" class="default-tag">默认</text>
          </view>
          <view class="address-detail">
            <text>{{address.city}} {{address.department}} {{address.houseNumber}}</text>
          </view>
        </view>
        <view class="item-footer">
          <view class="actions">
            <view class="edit-btn" @click.stop="editAddress(address)">
              <uni-icons type="compose" size="20" color="#666"></uni-icons>
              <text class="btn-text">编辑</text>
            </view>
            <view class="delete-btn" @click.stop="deleteAddress(address)">
              <uni-icons type="trash" size="20" color="#666"></uni-icons>
              <text class="btn-text">删除</text>
            </view>
          </view>
          <view v-if="isFromOrder" class="select-tip">
            <text>点击选择</text>
            <text class="arrow">›</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import Config from '@/Config.js'

export default {
  data() {
    return {
      addresses: [],
      userId: '', // 将从storage中获取
      isFromOrder: false // 是否从确认订单页面进入
    }
  },
  onLoad(options) {
    // 从storage中获取当前用户ID
    const userInfo = uni.getStorageSync('userInfo');
    if (userInfo) {
      this.userId = JSON.parse(userInfo)._id;
    }
    // 判断是否从确认订单页面进入
    this.isFromOrder = Boolean(options.from === 'order');
    this.fetchAddresses()
  },
  onShow() {
    // 每次页面显示时重新获取用户ID和地址列表
    const userInfo = uni.getStorageSync('userInfo');
    if (userInfo) {
      this.userId = JSON.parse(userInfo)._id;
      this.fetchAddresses();
    }
  },
  methods: {
    selectAddress(address) {
      if (!this.isFromOrder) return;
      
      // 将选中的地址信息存储到本地
      const addressInfo = {
        name: address.name,
        phone: address.phone,
        address: `${address.city} ${address.department} ${address.houseNumber}`,
        isDefault: address.isDefault,
        userId: this.userId // 添加用户ID标识
      };
      uni.setStorageSync('userAddress', JSON.stringify(addressInfo));
      
      // 触发地址变化事件
      uni.$emit('addressChanged');
      
      // 显示选择成功提示
      uni.showToast({
        title: '已选择该地址',
        icon: 'success',
        duration: 1500
      });
      
      // 返回上一页
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    },
    async fetchAddresses() {
      try {
        const response = await uni.request({
          url: Config.URL + 'users',
          method: 'GET'
        })
        
        if (response.statusCode === 200) {
          const users = response.data;
          const currentUser = users.find(user => String(user.id) === String(this.userId));
          if (currentUser && currentUser.addresses) {
            this.addresses = currentUser.addresses;
          } else {
            this.addresses = [];
          }
        } else {
          throw new Error('Failed to fetch addresses');
        }
      } catch (error) {
        uni.showToast({
          title: '获取地址失败',
          icon: 'none'
        })
      }
    },
    createNewAddress() {
      uni.navigateTo({
        url: '/pages/me/address-edit'
      })
    },
    editAddress(address) {
      uni.navigateTo({
        url: `/pages/me/address-edit?address=${encodeURIComponent(JSON.stringify(address))}`
      })
    },
    async deleteAddress(address) {
      try {
        const res = await uni.showModal({
          title: '提示',
          content: '确定要删除这个地址吗？',
          confirmText: '确定',
          cancelText: '取消'
        });
        
        if (!res.confirm) return;
        
        // 确保有用户ID和地址ID
        if (!this.userId || !address.id) {
          uni.showToast({
            title: '参数错误',
            icon: 'none'
          });
          return;
        }

        // 更新API路径结构
        const response = await uni.request({
          url: Config.URL + `users/${String(this.userId)}`,
          method: 'PATCH',
          header: {
            'content-type': 'application/json'
          },
          data: {
            addresses: this.addresses.filter(addr => addr.id !== address.id)
          }
        });
        
        if (response.statusCode === 200) {
          uni.showToast({
            title: '删除成功',
            icon: 'success'
          });
          
          // 更新本地存储的用户信息
          const userInfo = uni.getStorageSync('userInfo');
          if (userInfo) {
            const parsedUserInfo = JSON.parse(userInfo);
            parsedUserInfo.addresses = this.addresses.filter(addr => addr.id !== address.id);
            uni.setStorageSync('userInfo', JSON.stringify(parsedUserInfo));
          }
          
          // 重新获取地址列表
          await this.fetchAddresses();
        } else {
          throw new Error(`删除失败: ${response.statusCode}`);
        }
      } catch (error) {
        console.error('删除地址失败:', error);
        uni.showToast({
          title: error.message || '删除失败',
          icon: 'none',
          duration: 2000
        });
      }
    }
  }
}
</script>

<style lang="scss">
.address-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 30rpx;
    background-color: #fff;
    border-bottom: 1px solid #eee;
    
    .title {
      font-size: 32rpx;
      font-weight: 500;
    }
    
    .new-btn {
      color: #333;
      font-size: 28rpx;
    }
  }
  
  .address-list {
    padding: 20rpx;
    
    .empty-tip {
      text-align: center;
      padding: 60rpx 0;
      color: #999;
      font-size: 28rpx;
      
      .add-tip {
        display: block;
        margin-top: 20rpx;
        font-size: 24rpx;
        color: #1b76f6;
      }
    }
    
    .address-item {
      background-color: #fff;
      border-radius: 12rpx;
      padding: 30rpx;
      margin-bottom: 20rpx;
      
      &.selectable {
        position: relative;
        
        &:active {
          background-color: #f9f9f9;
        }
      }
      
      .address-content {
        margin-bottom: 20rpx;
        
        .contact-info {
          display: flex;
          align-items: center;
          margin-bottom: 20rpx;
          
          .name {
            font-size: 30rpx;
            margin-right: 30rpx;
          }
          
          .phone {
            font-size: 30rpx;
            color: #666;
            margin-right: 20rpx;
          }

          .default-tag {
            font-size: 24rpx;
            color: #ff6b6b;
            border: 1px solid #ff6b6b;
            padding: 2rpx 10rpx;
            border-radius: 4rpx;
          }
        }
        
        .address-detail {
          font-size: 28rpx;
          color: #333;
        }
      }
      
      .item-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-top: 20rpx;
        border-top: 1px solid #eee;
        
        .actions {
          display: flex;
          gap: 30rpx;
          
          .edit-btn, .delete-btn {
            display: flex;
            align-items: center;
            padding: 10rpx;
            
            .btn-text {
              font-size: 24rpx;
              color: #666;
              margin-left: 4rpx;
            }
            
            &:active {
              opacity: 0.7;
            }
          }
        }
        
        .select-tip {
          display: flex;
          align-items: center;
          font-size: 24rpx;
          color: #1b76f6;
          
          .arrow {
            font-size: 32rpx;
            margin-left: 4rpx;
          }
        }
      }
    }
  }
}
</style>